import React from 'react';
import { useNavigate } from 'react-router-dom';
import { Menu, Layout, message } from 'antd';
import SysMenus from '../../mock/AllMenus';
import './index.scss'
const { Sider } = Layout;

const Sidebar = () => {
  const navigate = useNavigate();
  const menuRouteClick = (e) => {
    let selectMenu = null;

    SysMenus.forEach(item => {
      if (item.key === e.key && item.skipPath) {
        selectMenu = item;
        return;
      }
      if (item.children) {
        const childItem = item.children.find(child => child.key === e.key && child.skipPath);
        if (childItem && childItem.skipPath) {
          selectMenu = childItem;
          return;
        }
      }
    });
    if(!selectMenu){
      message.warning('请确认是否存在该菜单信息');
      return;
    }
    navigate(selectMenu.skipPath); 
  };

  // 动态导入图标组件(后台菜单接口返回图标字符串，需转换为图标组件)
  const getIcon = (iconName) => {
    if (!iconName) return null;
    const IconComponent = require('@ant-design/icons')[iconName];
    return IconComponent ? <IconComponent /> : null;
  };

  // 传给Menu组件的items，过滤掉skipPath属性,不识别控制台报警
  const filterItems = (items) => {
    return items.map(item => {
      const { skipPath, ...rest } = item;
      if (item.icon) {
        rest.icon = getIcon(item.icon); // 动态获取图标
      }
      if (item.children) {
        rest.children = filterItems(item.children);
      }
      return rest;
    });
  };

  const filteredItems = filterItems(SysMenus);
  return (
    <Sider className='sidebar-box' collapsible>
      <Menu
        // defaultSelectedKeys={['1']}
        // defaultOpenKeys={['sub1']}
        mode="inline"
        theme="dark"
        items={filteredItems}
        onClick={ menuRouteClick}
      />
    </Sider>
  );
};
export default Sidebar;